package com.topisv.tms.web.occupiedAreaConfig;

import java.io.PrintWriter;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.occupiedArea.OarRecountPlan;
import com.topisv.tms.entity.occupiedArea.OccupiedAreaConfig;
import com.topisv.tms.entity.occupiedArea.OccupiedAreaConfigVo;
import com.topisv.tms.entity.occupiedArea.OccupiedAreaResult;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.WarehouseAgeService;
import com.topisv.tms.service.occupiedArea.OarRecountPlanService;
import com.topisv.tms.service.occupiedArea.OccupiedAreaConfigService;
import com.topisv.tms.service.task.ScheduledTaskService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.web.base.BaseController;

/**
 * 占用率配置_control
 * @author ch
 */
@Controller
@RequestMapping({ "/occupiedAreaConfig" })
public class OccupiedAreaConfigController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(OccupiedAreaConfigController.class);

	@Autowired
	private OccupiedAreaConfigService occupiedAreaConfigService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private WarehouseAgeService service;
	@Autowired
	private ScheduledTaskService scheduledTaskService;
	@Autowired
	private AreaGroupService areaGroupService;
	/**
	 * 配置查询页面
	 */
	@RequestMapping(value = "v2_occupiedAreaPage")
	public String warehouseAgePage(Model model, ServletRequest request,
			ServletResponse response) {
		fillSelectValue(model, null);
		return "/occupiedArea/occupiedAreaPage";
	}
	@RequestMapping(value = "v2_addOccupiedAreaConfigPage")
	public String addOccupiedAreaConfigPage(Model model, ServletRequest request,
			ServletResponse response) {
		fillSelectValue(model, null);
		return "/occupiedArea/addOccupiedAreaConfigPage";
	}
	
	
	@RequestMapping(value = "v2_saveOccupiedAreaConfig")
	public String saveOccupiedAreaConfigs(@ModelAttribute("vo")OccupiedAreaConfigVo occupiedAreaConfigVo,Model model, ServletRequest request,
			ServletResponse response) {
		if(occupiedAreaConfigVo==null||occupiedAreaConfigVo.getOacList() == null||occupiedAreaConfigVo.getOacList().size()==0){
			fillSelectValue(model, null);
			return "redirect:/occupiedArea/v2_occupiedAreaPage";
		}
		occupiedAreaConfigService.saveBatch(occupiedAreaConfigVo.getOacList());
		fillSelectValue(model, null);
		return "redirect:/occupiedArea/v2_occupiedAreaPage";
	}
	
	@RequestMapping(value = "ajaxSave")
	public void ajaxSave(@ModelAttribute("vo")OccupiedAreaConfig oac,Model model, ServletRequest request,
			ServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			if(oac.getId()==null||oac.getId()==0){
				json.put("msg", "success");
				json.put("content", "保存失败");
				return;
			}
			occupiedAreaConfigService.save(oac);
			json.put("msg", "success");
			json.put("content", "保存成功");
		} catch (NumberFormatException e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		} catch (Exception e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	@RequestMapping(value = "deleteOccupiedAreaConfig")
	public void deleteOccupiedAreaConfig(@RequestParam(value = "id") String id,Model model, ServletRequest request,
			ServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			
			occupiedAreaConfigService.delete(Long.valueOf(id));
			json.put("msg", "success");
			json.put("content", "删除成功");
		} catch (NumberFormatException e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		} catch (Exception e) {e.printStackTrace();
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		}
		fillSelectValue(model, null);
		out.print(json.toString());
	}
	
	@RequestMapping(value = "findOccupiedAreaConfigById")
	public void findOccupiedAreaConfig(@RequestParam(value = "id") String id,HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=new JSONObject();
		PrintWriter out=null;
		try{
			//变量定义
			out=response.getWriter();
			
			
			OccupiedAreaConfig oac = occupiedAreaConfigService.findById(Long.valueOf(id));

			//封装查询结果
	        json.put("oac", oac);
	        json.put("msg", "success");
			json.put("content", "查询成功");
		} catch (Exception e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	@RequestMapping(value = "findOccupiedAreaConfig")
	public void findOccupiedAreaConfig(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=new JSONObject();
		Page<OccupiedAreaConfig> page=null;
		PrintWriter out=null;
		try{
			//变量定义
			out=response.getWriter();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			//查询
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int pageSize = Integer.parseInt(paramMap.get("iDisplayLength")); 
			int pageNumber=(start/pageSize)+1;
			
			String customerCode = paramMap.get("customerCode");
			String warehouseCode = paramMap.get("warehouseCode");
			
			page = occupiedAreaConfigService.findBy(warehouseCode, customerCode,pageNumber,pageSize);
			List<OccupiedAreaConfig> oacList = page.getContent();

			//封装查询结果
	        json.put("aaData", oacList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
		} catch (Exception e) {
			log.error("查询异常",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	@Autowired
	private OarRecountPlanService orpService;
	
	@RequestMapping(value = "createRecountPlan")
	public void createRecountPlan(@RequestParam(value = "warehouseCode")final String warehouseCode,@RequestParam(value = "customerCode") final String customerCode,
			@RequestParam(value = "startTime") final String startTime,@RequestParam(value = "endTime") final String endTime,
			HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=new JSONObject();
		PrintWriter out=null;
		try{
			//变量定义
			out=response.getWriter();
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			if(format.parse(startTime).getTime()>format.parse(endTime).getTime()){
				json.put("msg", "startTimeOverEndTime");
				json.put("content", "开始时间不能大于结束时间");
				out.print(json.toString());
				return;
			}
			OccupiedAreaConfig config = occupiedAreaConfigService.findByCustomerCodeAndwarehouseCode(customerCode, warehouseCode);
			if(config==null){
				json.put("msg", "fail");
				json.put("content", "该仓库未配置仓租信息，");
				out.print(json.toString());
				return;
			}
			List<OarRecountPlan> orpList = occupiedAreaConfigService.findRecountPlan(warehouseCode, customerCode,startTime,endTime);
			if(orpList.size()==0){
				new RecountThread(warehouseCode, customerCode,startTime,endTime).start();
			}else {
				json.put("msg", "fail");
				json.put("content", "该时段有未计算完成计划，");
				out.print(json.toString());
				return;
			}
			//封装查询结果
	        json.put("msg", "success");
			json.put("content", "重算计划完成");
		} catch (Exception e) {e.printStackTrace();
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
			if("already_exists".equals(e.getMessage())){
				json.put("content", "该时段有未计算完成计划，");
			}
		}
		out.print(json.toString());
	}
	class RecountThread extends Thread {
		private String warehouseCode;
		private String customerCode;
		private String startTime;
		private String endTime;
		RecountThread( String warehouseCode, String customerCode,String startTime, String endTime){
			this.warehouseCode = warehouseCode;
			this.customerCode = customerCode;
			this.startTime = startTime;
			this.endTime = endTime;
		}
		public void run(){
			try {
				occupiedAreaConfigService.recountOccupiedAreaResult(warehouseCode, customerCode,startTime,endTime);
			} catch (Exception e) {
				try {
					List<OarRecountPlan>  orpList = occupiedAreaConfigService.findRecountPlan(warehouseCode, customerCode, startTime, endTime);
					for (OarRecountPlan orp : orpList) {
						orp.setStatus("error");
						orpService.save(orp);
					}
				} catch (Exception e1) {
					log.error("重算仓租报错",e1);
				}
				log.error("重算仓租报错",e);
			}
		}
	}
	
	@RequestMapping(value = "queryRecountPlan")
	public void queryRecountPlan(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=new JSONObject();
		PrintWriter out=null;
		try{
			//变量定义
			out=response.getWriter();
			
			List<OarRecountPlan> orpList = occupiedAreaConfigService.findRecountPlan(null,null,null,null);
			if(orpList.size()==0){
				orpList = occupiedAreaConfigService.findRecountPlanLatelyForFinish();
				json.put("doing", "false");
			}else {
				json.put("doing", "true");
				
			}
			
			//封装查询结果
			json.put("msg", "success");
	        json.put("orpList", orpList);
			json.put("content", "查询成功");
		} catch (Exception e) {e.printStackTrace();
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
			if("already_exists".equals(e.getMessage())){
				json.put("content", "该时段有未计算完成计划，");
			}
		}
		out.print(json.toString());
	}
	
	@RequestMapping(value = "v2_occupiedAreaResultPage")
	public String occupiedAreaReslultPage(Model model, ServletRequest request,
			ServletResponse response) {
		fillSelectValue(model, null);
		return "/occupiedArea/occupiedAreaResultPage";
	}
	
	@RequestMapping(value = "findOccupiedAreaReslult")
	public void findOccupiedAreaReslult(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=new JSONObject();
		PrintWriter out=null;
		try{
			//变量定义
			out=response.getWriter();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			//查询
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int pageSize = Integer.parseInt(paramMap.get("iDisplayLength")); 
			int pageNumber=(start/pageSize)+1;
			
			String customerCode = paramMap.get("customerCode");
			String warehouseCode = paramMap.get("warehouseCode");
			String startTime = paramMap.get("startTime")+" 00:00:00:000";
			String endTime = paramMap.get("endTime")+" 23:59:59:999";
			
			List<OccupiedAreaResult> oarList =occupiedAreaConfigService.findByResult(warehouseCode, customerCode,startTime,endTime,pageNumber,pageSize);
			
			BigInteger totalNum =occupiedAreaConfigService.findByResultTotalNum(warehouseCode, customerCode,startTime,endTime,pageNumber,pageSize);
			
			//封装查询结果
	        json.put("aaData", oarList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords",totalNum);
	        json.put("iTotalDisplayRecords", pageSize);
		} catch (Exception e) {e.printStackTrace();
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	
	
	@RequestMapping(value = "exportOccupiedAreaReslult")
	public String exportOccupiedAreaReslult(@RequestParam(value = "warehouseCode") String warehouseCode,@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "startTime") String startTime,@RequestParam(value = "endTime") String endTime,HttpServletRequest request, HttpServletResponse response) {
		try{
			//变量定义
			String fileName = "仓租结算清单";
			if(!StringUtils.isEmpty(customerCode)){
				fileName += "_" + customerCode;
			}
			if(!StringUtils.isEmpty(warehouseCode)){
				fileName += "_" + warehouseCode;
			}
			if(!StringUtils.isEmpty(startTime)){
				fileName += "_" + startTime;
			}
			if(!StringUtils.isEmpty(startTime)){
				fileName += "_" + endTime;
			}
			
			startTime = startTime+" 00:00:00:000";
			endTime = endTime+" 23:59:59:999";
			
			List<OccupiedAreaResult> oarList =occupiedAreaConfigService.findByResult(warehouseCode, customerCode,startTime,endTime,0,0);
			
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition","attachment; filename=" + new String((fileName).getBytes("gbk"),"iso8859-1") + ".xls");
			WritableWorkbook book  =  Workbook.createWorkbook(response.getOutputStream());
			
			
			int sheetIndex = 0;
			int rowIndex = 0;
			while(true){
				WritableSheet sheet  =  book.createSheet( "库龄信息( 第"+(sheetIndex+1)+"页)",sheetIndex);
				sheet.setColumnView(0, 20);//商家编码
				sheet.setColumnView(1, 20);//仓库编码
				sheet.setColumnView(2, 20);//SKU
				sheet.setColumnView(3, 20);//结算时间
				sheet.setColumnView(4, 20);//超时开始时间
				sheet.setColumnView(5, 20);//超时结束时间
				sheet.setColumnView(6, 15);//超时天数
				sheet.setColumnView(7, 15);//超龄数量
				sheet.setColumnView(8, 25);//当前状态
				
				int index = 0;
				Label label1 = new  Label(0,index ,"商家编码");
				sheet.addCell(label1);
				Label label2 = new  Label(1,index ,"仓库编码");
				sheet.addCell(label2);
				Label label3 = new  Label(2,index ,"超出总面积");
				sheet.addCell(label3);
				Label label4 = new  Label(3,index ,"超出总金额");
				sheet.addCell(label4);
				Label label5 = new  Label(4,index ,"库位总成本");
				sheet.addCell(label5);
				Label label6 = new  Label(5,index ,"结算开始时间");
				sheet.addCell(label6);
				Label label7 = new  Label(6,index ,"结算结束时间");
				sheet.addCell(label7);
				
				while(true){
//				for(int i = rowIndex ; i < soiList.size();i++) {
					if(index == 60000||rowIndex>=oarList.size()){
						break;
					}
					OccupiedAreaResult soi = oarList.get(rowIndex);
					index++;
					rowIndex++;
					Label label11 = new  Label(0,index ,soi.getCustomerCode());
					sheet.addCell(label11);
					Label label12 = new  Label(1,index ,soi.getWarehouseCode());
					sheet.addCell(label12);
					Label label13 = new  Label(2,index ,soi.getOverArea()+"");
					sheet.addCell(label13);
					Label label14 = new  Label(3,index ,soi.getOverTotalPrice()+"");
					sheet.addCell(label14);
					Label label15 = new  Label(4,index ,soi.getTotalCost()+"");
					sheet.addCell(label15);
					Label label16 = new  Label(5,index ,startTime);
					sheet.addCell(label16);
					Label label17 = new  Label(6,index ,endTime);
					sheet.addCell(label17);
				}
				System.out.println(rowIndex);
				if(rowIndex>=oarList.size()){
					break;
				}
				sheetIndex++;
			}
			logger.info("导出成功");
			book.write();
            book.close();
            
			//封装查询结果
		} catch (Exception e) {
			log.error("导出仓租结算清单",e);
			return "false";
		}
		return "true";
	}
}


